/* js/rpwd.js */
$(document).ready(function() {
    const token = localStorage.getItem('token');
    const userId = localStorage.getItem('user_id');
  
    if (!token || !userId) {
      alert('请先登录');
      window.location.href = 'login.html';
      return;
    }
  
    // 简单校验
    function pwdTest(password) {
      // 6-12位，数字字母下划线
      const pwdRegex = /^\w{6,12}$/;
      return pwdRegex.test(password);
    }
  
    $('#rpwdForm').on('submit', function(e) {
      e.preventDefault();
      const oldPassword = $('.oldpassword').val().trim();
      const newPassword = $('.newpassword').val().trim();
      const rNewPassword = $('.rnewpassword').val().trim();
  
      if (!oldPassword || !newPassword || !rNewPassword) {
        alert('所有字段都是必填项');
        return;
      }
      if (newPassword !== rNewPassword) {
        alert('两次输入的新密码不一致');
        return;
      }
      if (!pwdTest(newPassword)) {
        alert('新密码格式错误');
        return;
      }
  
      axios.post('http://localhost:8888/users/rpwd', {
        id: userId,
        oldPassword,
        newPassword,
        rNewPassword
      }, {
        headers: { 'Authorization': token }
      })
      .then(response => {
        if (response.data.code === 1) {
          localStorage.removeItem('token');
          localStorage.removeItem('user_id');
          alert('修改密码成功，请重新登录');
          window.location.href = 'login.html';
        } else {
          alert('修改密码失败：' + response.data.message);
        }
      })
      .catch(error => {
        console.error('修改密码请求出错：', error);
        alert('修改密码请求出错，请稍后重试');
      });
    });
  });
  